import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    systemFlag: '',
    breedType: '',
    breedType_template: '',
    breedTypeList: [],
    isGuide: false,
    routerOffsetTop: '',
    guideInfo: {
      procedure: [],
      index: 0
    }
  }
}

const state = getDefaultState()
const breedTypeObj = {
  "DSYZ": "HANGING_WATER_BREED",
  "CTYZ": "TRADITION_BREED",
  "XHSYZ": "CIRCULATE_BREED",
  "PDYZ": "RUNWAY_BREED"
}
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_GUIDE: (state, flag) => {
    state.isGuide = flag
  },
  SET_ROUTEROPERATION: (state, info) => {
    state.routerOffsetTop = info
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_SYSTEM_FLAG: (state, flag) => {
    state.systemFlag = flag
  },
  GET_GUIDE_INFO: (state, info) => {
    state.guideInfo = info
  },
  SET_BEED_FLAG: (state, flag) => {
    state.breedType = flag
    state.breedType_template = breedTypeObj[flag] || '';
    sessionStorage.setItem('breedType', breedTypeObj[flag] || '')
  },
  SET_BREEDTYPELIST: (state, list) => {
    state.breedTypeList = list
  },
}

const actions = {
  setBreedTypeList({ commit }, list) {
    if (list.length == 0) {
      Message.warning('未配置养殖类型，请联系管理员配置!')
    }
    commit('SET_BREEDTYPELIST', list)
  },
  setGuide({ commit }, falg) {
    commit('SET_GUIDE', falg)
  },
  getGuideInfo({ commit }, info) {
    commit('GET_GUIDE_INFO', info)
  },
  getRouterOperation({ commit }, info) {
    commit('SET_ROUTEROPERATION', info)
  },
  login({ commit }, logInfo) {
    const { account, password } = logInfo
    return new Promise((resolve, reject) => {
      login({ username: account.trim(), password: password }).then(res => {
        const { data } = res
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      commit('SET_TOKEN', '')
      resolve({})
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken();
      resetRouter();
      commit('RESET_STATE');
      resolve();
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

